package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;

    @Override
    public PageResult<Emp> getPageResult(EmpQueryParam param) {
        //设置分页参数
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        //进行分页条件查询
        page = lambdaQuery()
                .like(param.getName() != null && ! param.getName().isEmpty(),Emp::getName, param.getName())
                .eq(param.getGender() != null,Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null,Emp::getEntryDate, param.getBegin(), param.getEnd())
                .orderByDesc(Emp::getUpdateTime)
                .page(page);

        //查询部门名称
        //.获取查询的员工集合
        List<Emp> emps = page.getRecords();
        log.info("员工集合：{}", emps);
        //.将查询到员工的id收集到Set集合中
        Set<Integer> empIds = emps.stream().map(Emp::getDeptId).collect(Collectors.toSet());
        //.根据id查询部门名称
        List<Dept> depts = deptService.listByIds(empIds);
        //.将部门的id和名称封装到Map集合中
        Map<Integer, String> deptMap = depts.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
        //.遍历员工集合，将部门名称存储到员工对象中，如果部门id为null，则部门名称为null
        emps.forEach(emp -> emp.setDeptName(deptMap.get(emp.getDeptId())));
        emps.forEach(emp -> emp.setDeptName(deptMap.getOrDefault(emp.getDeptId(), null)));

        return new PageResult<>(page.getTotal(), page.getRecords());
    }

    @Transactional
    @Override
    public void saveEmp(Emp emp) {
        //保存员工基本信息
        //补全基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);
        //获取工作经历
        List<EmpExpr> empExprs = emp.getExprList();
        //遍历为工作经历增加员工id
        if (!empExprs.isEmpty()){
            empExprs.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
        }
        //保存员工工作经历
        empExprService.saveBatch(empExprs);
    }

    @Transactional
    @Override
    public Emp getEmpById(Integer id) {
        //查询员工基本信息
        Emp emp = empMapper.selectById(id);
        //查询员工基本经历
        List<EmpExpr> empExprs = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id));
        emp.setExprList(empExprs);
        return emp;
    }

    @Transactional
    @Override
    public void updateEmp(Emp emp) {
        //保存员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);
        //删除员工工作经历
        empExprService.removeById(emp.getId());
        //获取工作经历
        List<EmpExpr> empExprs = emp.getExprList();
        //遍历为工作经历增加员工id
        if (!empExprs.isEmpty()){
            empExprs.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
        }
        //保存员工工作经历
        empExprService.saveBatch(empExprs);
    }

    @Transactional
    @Override
    public void deleteEmpById(List<Integer> ids) {
        //删除员工基本信息
        removeByIds(ids);
        //删除员工的工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids));
    }
}
